package org.yq.timer;

import java.util.ArrayList;
import java.util.List; 
import java.util.TimerTask;

public class TimerCollection {	
	private static List<SuperTimer> LIST_TIMER = new ArrayList<SuperTimer>();
	
	public static void startTimer(TimerBean bean){
		boolean flag = false;
		for(SuperTimer t : LIST_TIMER){
			if(t.getId().equals(bean.getId())){
				flag = true;//exists this id 
				break;
			}
		}
		if(!flag){
			SuperTimer timer = new SuperTimer(bean.getId());
			try {
				TimerTask timerTask = (TimerTask)Class.forName(bean.getClsName()).newInstance();
				timer.schedule(timerTask, bean.getDelay().longValue(), bean.getPeriod().longValue());
			} catch (Exception e) { 
				e.printStackTrace();
			} 
			LIST_TIMER.add(timer);
		}
	}
	
	public static void stopTimer(String id){
		int ind = 0;
		for(SuperTimer t : LIST_TIMER){
			if(t.getId().equals(id)){
				t.cancel();
				LIST_TIMER.remove(ind);
				break;
			}
			ind++;
		}
	}
	
	public static void stopAllTimer(){
		int ind = 0;
		for(SuperTimer t : LIST_TIMER){
			t.cancel();
			LIST_TIMER.remove(ind);
			ind++;
		}
	}
	
	public static void updateTimer(TimerBean bean){
		stopTimer(bean.getId());
		startTimer(bean);
	}
	
	public static List<SuperTimer> getTimers(){
		return LIST_TIMER;
	}
	
	public static boolean execute(TimerBean bean){
		boolean flag = false;
		try {
			TimerTask timerTask = (TimerTask)Class.forName(bean.getClsName()).newInstance();
			timerTask.run();
			flag = true;
		} catch (Exception e) { 
			e.printStackTrace();
		} 
		return flag;
	}
	
}
